package com.fzb.zrlog.simple.controller;

import com.fzb.common.Constant;
import com.fzb.zrlog.simple.dao.api.*;
import com.fzb.zrlog.simple.dao.impl.*;
import com.hibegin.http.server.api.HttpRequest;
import com.hibegin.http.server.api.HttpResponse;
import com.hibegin.http.server.web.Controller;
import com.hibegin.http.server.web.cookie.Cookie;
import com.hibegin.http.server.web.session.HttpSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BaseControl extends Controller implements Constant {

    private static final Map<String, Object> webContext = new ConcurrentHashMap<>();
    private String templatePath;
    private Integer rows;
    private Map<String, Object> webSite;

    public BaseControl(HttpRequest request, HttpResponse response) {
        super(request, response);
        initData();
    }

    public static void refreshCache() {

    }

    public void initData() {
        Map<String, Object> init = (Map) getRequest().getSession().getAttr("init");
        if (init == null) {
            ILogDAO logDAO = new Log();
            IWebSiteDAO webSiteDAO = new WebSite();
            ILinkDAO linkDAO = new Link();
            ITypeDAO typeDAO = new Type();
            ITagDAO tagDAO = new Tag();
            IPluginDAO pluginDAO = new Plugin();
            ILogNavDAO logNavDAO = new LogNav();

            init = getRequest().getAttr();
            List<Map<String, Object>> types = typeDAO.queryAll();
            init.put("webSite", webSiteDAO.getWebSite());
            init.put("links", linkDAO.queryAll());
            init.put("types", types);
            init.put("logNavs", logNavDAO.queryAll("http://" + getRequest().getHeader("Host")));
            init.put("plugins", pluginDAO.queryAll());
            init.put("archives", logDAO.getArchives());
            init.put("tags", tagDAO.queryAll());
            init.put("hotLog", logDAO.getLogsByPage(1, 6));
            init.put("version", "0.1");
            init.put("system", System.getProperties());
            getRequest().getSession().setAttr("init", init);
        }
        getRequest().getAttr().putAll(init);
        webSite = (Map) init.get("webSite");
        this.rows = Integer.parseInt(getStrValuebyKey("rows"));
        this.templatePath = getStrValuebyKey("template");

        setAttr("url", "http://" + getRequest().getHeader("Host") + "/");
        setAttr("templateUrl", "http://" + getRequest().getHeader("Host") + getTemplatePath());
        setAttr("currentUrl", getRequest().getFullUrl());
        setAttr("param", request.getParamMap());
    }

    public String getTemplatePath() {
        return this.templatePath;
    }

    public Integer getDefaultRows() {
        return this.rows;
    }

    public Object getValuebyKey(String key) {
        if (webSite.get(key) != null) {
            return webSite.get(key).toString();
        }
        return null;
    }

    public String getStrValuebyKey(String key) {
        if (webSite.get(key) != null) {
            return webSite.get(key).toString();
        }
        return null;
    }

    public boolean isNotNullOrNotEmptyStr(Object... args) {
        for (Object arg : args) {
            if (arg == null) {
                return false;
            } else if ("".equals(arg)) {
                return false;
            }
        }
        return true;
    }

    public void setAttr(String name, Object obj) {
        if (obj != null) {
            getRequest().getAttr().put(name, obj);
        } else {
            getRequest().getAttr().put(name, new HashMap<>());
        }
    }

    public String getPara(int idx) {
        String[] str = getRequest().getUri().substring(getRequest().getUri().lastIndexOf("/") + 1).split("-");
        if (str.length > 0) {
            return str[idx];
        }
        return null;
    }

    public String getPara(String key) {
        String[] vs = getRequest().getParamMap().get(key);
        return vs != null ? vs[0] : null;
    }

    public Integer getParaToInt(int idx, int defaultValue) {
        try {
            return Integer.parseInt(getPara(idx) + "");
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public Integer getParaToInt(int idx) {
        return getParaToInt(idx, 0);
    }

    public Cookie getCookie(String key) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                return cookie;
            }
        }
        return null;
    }

    public HttpSession getSession() {
        return request.getSession();
    }

    public Map<String, Object> getWebContext() {
        return webContext;
    }

    public Object getSessionAttr(String key) {
        return getRequest().getSession().getAttr(key);
    }

}
